﻿@using DCMS.Web.Framework.UI;
@using DCMS.Web.Framework;
@using DCMS.Core.Domain.Common;
@using DCMS.ViewModel.Models.Sales;

@model DispatchBillListModel

<style type="text/css">
    .fixed-table-body {
        overflow-x: hidden;
        overflow-y: auto;
    }
</style>

<section id="content_wrapper">

    <!-- Start: Topbar-Dropdown -->
    <div id="topbar-dropmenu">
        @await Html.PartialAsync("_ToolBox")
    </div>
    <!-- End: Topbar-Dropdown -->
    <!-- Start: Topbar -->
    <header id="topbar">
        <div class="topbar-left">
            <ol class="breadcrumb">
                <li class="crumb-active">
                    <a href="#">装车调度单管理</a>
                </li>
                <li class="crumb-icon">
                    <a href="@Url.RouteUrl("HomePage")">
                        <span class="glyphicon glyphicon-home"></span>
                    </a>
                </li>
                <li class="crumb-link">
                    <a href="#">销售管理</a>
                </li>
                <li class="crumb-trail">装车调度单</li>
            </ol>
        </div>
        <div class="topbar-right">
            <div class="ml15 ib va-m" id="toggle_sidemenu_r">
                <a href="#" class="pl5">
                    <i class="fa fa-sign-in fs22 text-primary"></i>
                    <span class="badge badge-hero badge-danger">3</span>
                </a>
            </div>
        </div>
    </header>
    <!-- End: Topbar -->
    <!-- Begin: Content -->
    <!-- End: Topbar -->
    <!-- Begin: Content -->
    <section id="content" class="formSection">

        <div class="special-alerts">
            <div class="alert alert-danger light alert-dismissable" id="alert-demo-2" style="display: none;">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                <i class="fa fa-info pr10"></i>
                <strong>您没有被授权此操作!</strong>
            </div>
        </div>

        <div class="row">
            <div class="col-md-12">

                <div class="panel panel-default" id="panel0">
                    <div class="panel-heading">
                        <span class="glyphicon glyphicon-search"></span> 高级搜索
                        <a class="btn btn-default btn-sm pull-right m5 mrn p5 pbn" id="AdvancedSearch"><i class="fa fa-angle-double-right mr5"></i>展开</a>
                    </div>
                    <div class="panel-body p10">
                        @*打印区域*@
                        <div id="printData" />
                        <form id="formSearch" class="form-horizontal" novalidate="novalidate">
                            <div class="row">
                                <div class=" col-sm-2">
                                    <dcms-editor asp-for="StartTime" placeholder="开始..." />
                                </div>
                                <div class=" col-sm-2">
                                    <dcms-editor asp-for="EndTime" placeholder="结束..." />
                                </div>
                                <div class="col-sm-2">
                                    <dcms-select asp-for="BusinessUserId" asp-items="@Model.BusinessUsers" asp-default="选择业务员" />
                                </div>
                                <div class="col-sm-2">
                                    <dcms-select asp-for="DistrictId" asp-items="@Model.Districts" asp-default="选择片区" />
                                </div>
                                <div class="col-sm-2">
                                    <input asp-for="TerminalId" type="hidden" />
                                    <div class="input-group">
                                        <input asp-for="TerminalName" class="form-control" placeholder="客户..." />
                                        <span class="input-group-btn">
                                            <button id="btn_search_customer" type="button" class="btn btn-default">
                                                <span class="glyphicon glyphicon-search"></span>
                                            </button>
                                        </span>
                                    </div>
                                </div>
                                <div class="col-sm-2">
                                    <input asp-for="BillNumber" class="form-control" placeholder="单据号..." />
                                </div>

                            </div>

                            <div class="row mt10 mb10">
                                <div class="col-sm-2">
                                    <dcms-select asp-for="DeliveryUserId" asp-items="@Model.DeliveryUsers" asp-default="选择配送员" />
                                </div>
                                <div class="col-sm-2">
                                    <dcms-select asp-for="ChannelId" asp-items="@Model.Channels" asp-default="选择渠道" />
                                </div>
                                <div class="col-sm-2">
                                    <dcms-select asp-for="RankId" asp-items="@Model.Ranks" asp-default="选择等级" />
                                </div>
                                <div class="col-sm-2">
                                    <dcms-select asp-for="BillTypeId" asp-items="@Model.BillTypes" asp-default="选择单据类型" />
                                </div>
                                <div class=" col-sm-2">
                                    <dcms-select-bool asp-for="ShowDispatchReserved" asp-items="@(new string[] {  "是", "否"})" asp-default="显示红冲调度单" />
                                </div>
                                <div class="col-sm-2">
                                    <button id="btn_query" type="button" class="btn btn-primary btn-block">
                                        <span class="glyphicon glyphicon-search mr5" aria-hidden="true"></span>查询
                                    </button>
                                </div>
                            </div>

                        </form>

                        <div class="row">

                            <div class="col-sm-1">
                                <button id="btn_dispatchBill" type="button" class="btn btn-success btn-block">
                                    <span class="glyphicon glyphicon-shopping-cart mr5" aria-hidden="true"></span>调度
                                </button>
                            </div>
                            <div class="col-sm-1">
                                <button id="btn_setwarehouse" type="button" class="btn btn-alert btn-block">
                                    <span class="glyphicon glyphicon-list-alt mr5" aria-hidden="true"></span>设置仓库
                                </button>
                            </div>

                        </div>
                    </div>
                </div>

                <div class="panel">
                    <div class="panel-heading">
                        <div class="panel-title">
                            <span class="glyphicon glyphicon-tasks"></span> 装车调度列表
                        </div>
                    </div>
                    <div class="panel-body p10">
                        @*--*@
                        <div class="tab-block">
                            <ul class="nav nav-tabs tabs-bg">
                                <li class="active">
                                    <a href="#tab10_1" data-toggle="tab" aria-expanded="true">
                                        <i class="fa fa-align-justify text-purple"></i> 待调度<span class="badge badge-hero badge-danger" id="badge1"></span>
                                    </a>
                                </li>
                                <li>
                                    <a href="#tab10_2" data-toggle="tab">
                                        <i class="fa fa-align-justify text-purple"></i> 已调度<span class="badge badge-hero badge-danger" id="badge2"></span>
                                    </a>
                                </li>
                            </ul>
                            <div class="tab-content">
                                <div id="tab10_1" class="tab-pane active">
                                    <table class="table table-striped table-bordered table-hover" id="datatable1"></table>
                                </div>
                                <div id="tab10_2" class="tab-pane">
                                    <table class="table table-striped table-bordered table-hover" id="datatable2" ></table>
                                </div>
                            </div>
                        </div>
                        @*--*@
                        @*<table class="table table-striped table-bordered table-hover" id="datatable"></table>*@
                        <div class="clearfix"></div>
                    </div>
                </div>
            </div>
        </div>

    </section>
</section>



@{
    @await Html.PartialAsync("_Windows", Model)
}



@section CurPageScripts
{

    <script type="text/javascript">

        function numberFormatter(value, row, index) {
            return m_pagerow + index + 1;
        }

        function strEnabledFormatter(value, row, index) {
            if (!value) {
                return '<span class="label label-denger">否</span>';
            } else {
                return '<span class="label label-success">是</span>';
            }
        }

        function nameFormatter(value, row) {
            var icon = row.Id % 2 === 0 ? 'glyphicon-star' : 'glyphicon-star-empty'
            return '<i class="glyphicon ' + icon + '"></i> ' + value;
        }

        function IconFormatter(value, row) {
            return '<i class="fa ' + value + '"></i>';
        }

        function priceFormatter(value) {
            // 16777215 == ffffff in decimal
            var color = '#' + Math.floor(Math.random() * 6777215).toString(16);
            return '<div  style="color: ' + color + '">' +
                '<i class="glyphicon glyphicon-usd"></i>' +
                value.substring(1) +
                '</div>';
        }

        // 格式化类型
        function typeFormatter(value, row, index) {
            if (value === 'menu') {
                return '菜单';
            }
            if (value === 'button') {
                return '按钮';
            }
            if (value === 'api') {
                return '接口';
            }
            return '-';
        }

        // 格式化状态
        function statusFormatter(value, row, index) {
            if (value) {
                return '<span class="label label-success">正常</span>';
            } else {
                return '<span class="label label-default">锁定</span>';
            }
        }

        var $table1 = $('#datatable1');
        var $table2 = $('#datatable2');

        jQuery(document).ready(function () {

            var oTableInit = new Object();

            "use strict";

            // Init Theme Core
            Core.init();

            // Init Demo JS
            Demo.init();

            //权限提示
            if ($(this).getUrlQueryString("Authorize") == "noAuthorize") {
                $('#alert-demo-2').fadeToggle();
                setTimeout(function () {
                    $('#alert-demo-2').fadeToggle();
                }, 3000);
            }

            //日期选择控件初始
            //$('.datetimepicker').datetimepicker({ locale: 'zh-cn', format: "YYYY-MM-DD hh:mm:ss");

            //高级搜索
            $("#panel0 #AdvancedSearch").click(function () {
                var ico = $(this).find(".fa");
                if (ico.hasClass('fa-angle-double-right'))
                    ico.removeClass("fa-angle-double-right").addClass("fa-angle-double-down");
                else
                    ico.removeClass("fa-angle-double-down").addClass("fa-angle-double-right");
                $("#panel0").find(".panel-body").toggleClass("hidden animated fadeIn");
            });

            //查询参数
            var dbQueryParams1 = function (params) {
                var temp =
                {
                    //时间
                    start: $("#StartTime").val(),
                    end: $("#EndTime").val(),
                    //业务员
                    businessUserId: $("#BusinessUserId").val(),
                    //片区
                    districtId: $("#DistrictId").val(),
                    //客户
                    terminalId: $("#TerminalId").val(),
                    //客户名称
                    terminalName: $("#TerminalName").val(),
                    //单据号
                    BillNumber: $("#BillNumber").val(),
                    //送货员
                    deliveryUserId: $("#DeliveryUserId").val(),
                    //客户渠道
                    channelId: $("#ChannelId").val(),
                    //客户等级
                    rankId: $("#RankId").val(),
                    //订单类型
                    billTypeId: $("#BillTypeId").val(),
                    //显示红冲调度单
                    showDispatchReserved: $("#ShowDispatchReserved").val(),
                    //调度状态
                    dispatchStatus: false,

                    pageSize: params.limit,   //页面显示行数
                    pageIndex: (params.offset / params.limit)  //页码
                };
                return temp;
            };


            //初始化表格
            var actionURL1 = "/DispatchBill/AsyncPending";
            var $formSection = $(".formSection");

            //初始 待调度
            $($table1).bootstrapTable({
                url: actionURL1,         //请求后台的URL（*）
                method: 'get',                      //请求方式（*）
                toolbar: '#toolbar',                //工具按钮用哪个容器
                striped: true,                      //是否显示行间隔色
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,                   //是否显示分页（*）
                sortable: true,                     //是否启用排序
                sortOrder: "asc",                   //排序方式
                queryParams: dbQueryParams1,//传递参数（*）
                sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                idField: 'Id',
                pageNumber: 1,                       //初始化加载第一页，默认第一页
                pageSize: 20,                       //每页的记录行数（*）
                pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
                search: false,
                strictSearch: true,
                showColumns: false,
                showRefresh: false,
                clickToSelect: true,
                uniqueId: "Id",
                showToggle: false,
                cardView: false,
                //detailView: false,
                detailView: false,
                showFooter: false,
                //columns: tbColumns,
                onExpandRow: function (index, row, $detail) {
                    var dispatchStatus = $("#DispatchStatus").val() == "0" ? false : ($("#DispatchStatus").val() == 1 ? true : false);
                    if (dispatchStatus) {
                        oTableInit.InitSubTable(index, row, $detail);
                    }
                },
                columns: [
                    { checkbox: true },
                    {
                        field: 'BillNumber',
                        title: '编号',
                        align: 'center',
                        width: '150',
                        formatter: function (value, row, index) {
                            if (row.BillTypeId == 11) {
                                return [
                                    '<a  href="/SaleReservationBill/Edit/' + row.BillId + '">' + row.BillNumber + '</a>'
                                ].join("")
                            } else if (row.BillTypeId == 10) {
                                return [
                                    '<a  href="/ExchangeBill/Edit/' + row.BillId + '">' + row.BillNumber + '</a>'
                                ].join("")
                            }
                            else if (row.BillTypeId == 13) {
                                return [
                                    '<a  href="/ReturnReservationBill/Edit/' + row.BillId + '">' + row.BillNumber + '</a>'
                                ].join("")
                            }
                        }
                    },
                    { field: 'CarNO', visible: false },
                    { field: 'BillId', visible: false },
                    { field: 'BillTypeName', title: '单据类型', align: 'left' },
                    {
                        field: 'TransactionDate', title: '交易时间', align: 'center', formatter: function (value, row, index) {
                            if (value != "") {
                                return $(this).dateFtt('yyyy-MM-dd hh:ss:mm', new Date(value));
                            }
                            else {
                                return "";
                            }

                        }
                    },
                    { field: 'BusinessUserName', title: '业务员', align: 'left' },
                    { field: 'DeliveryUserId', visible: false },
                    { field: 'DeliveryUserName', title: '送货员', align: 'left' },
                    { field: 'TerminalName', title: '客户', align: 'left' },
                    { field: 'TerminalAddress', title: '客户地址', align: 'left' },
                    { field: 'OrderAmount', title: '订单金额', align: 'right' },
                    { field: 'WareHouseName', title: '出货/入货仓库', align: 'left' },
                    { field: 'OrderQuantityView', title: '销售商品数量', align: 'right' },
                    {
                        field: 'SignStatus',
                        title: '数据来源',
                        align: 'center',
                        width: 70,
                        formatter: function (value, row, index) {
                            if (value == 0) {
                                return '<span class="label label-info">线上</span>';
                            } else {
                                return '<span class="label label-info">线下</span>';
                            }
                        }
                    },
                    { field: 'Remark', title: '备注', align: 'left' },

                ],

                onPageChange: function (number, size) {
                    m_pagerow = (number - 1) * size;
                },
                treeShowField: 'Name',
                parentIdField: 'ParentId',
                onLoadSuccess: function (data) {
                    $("#badge1").html($($table1).bootstrapTable('getData').length);
                }
            });


            //查询参数
            var dbQueryParams2 = function (params) {
                var temp =
                {
                    //时间
                    start: $("#datetimepicker_StartTime").val(),
                    end: $("#datetimepicker_EndTime").val(),
                    //业务员
                    businessUserId: $("#BusinessUserId").val(),
                    //片区
                    districtId: $("#DistrictId").val(),
                    //客户
                    terminalId: $("#TerminalId").val(),
                    //客户名称
                    terminalName: $("#TerminalName").val(),
                    //单据号
                    BillNumber: $("#BillNumber").val(),
                    //送货员
                    deliveryUserId: $("#DeliveryUserId").val(),
                    //客户渠道
                    channelId: $("#ChannelId").val(),
                    //客户等级
                    rankId: $("#RankId").val(),
                    //订单类型
                    billTypeId: $("#BillTypeId").val(),
                    //显示红冲调度单
                    showDispatchReserved: $("#ShowDispatchReserved").val(),
                    //调度状态
                    dispatchStatus: true,

                    pageSize: params.limit,   //页面显示行数
                    pageIndex: (params.offset / params.limit)  //页码
                };
                return temp;
            };
            //初始化表格
            var actionURL2 = "/DispatchBill/AsyncCompleted";
            //初始 已调度
            $($table2).bootstrapTable({
                url: actionURL2,
                method: 'get',
                toolbar: '#toolbar',
                striped: true,
                cache: false,
                pagination: true,
                sortable: true,
                sortOrder: "asc",
                queryParams: dbQueryParams2,
                sidePagination: "server",
                idField: 'Id',
                pageNumber: 1,
                pageSize: 20,
                pageList: [10, 25, 50, 100],
                search: false,
                strictSearch: true,
                showColumns: false,
                showRefresh: false,
                clickToSelect: true,
                uniqueId: "Id",
                showToggle: false,
                cardView: false,
                detailView: true,
                showFooter: false,
                onExpandRow: function (index, row, $detail) {
                    oTableInit.InitSubTable(index, row, $detail);
                },
                columns: [
                    //{ checkbox: false },
                    {
                        field: 'BillNumber', title: '编号',
                        align: 'left',
                        width: 200,
                        formatter: function (value, row, index) {
                            if (row.BillTypeId == 18) {
                                return [
                                    '<a href="/DispatchBill/Edit/' + row.Id + '">' + row.BillNumber + '</a>' + '<div>' + row.CarNO + '</div>'
                                ].join("")
                            }
                        }
                    },
                    { field: 'CarNO', visible: false },
                    { field: 'BillTypeName', title: '单据类型', align: 'left', width: 100 },
                    {
                        field: 'CreatedOnUtc', title: '交易时间',
                        align: 'center',
                        width: 150,
                        formatter: function (value, row, index) {
							if (value != "" && value!=undefined) {
                                return $(this).dateFtt('yyyy-MM-dd hh:ss:mm', new Date(value));
                            }
                            else
                            {
                                return "";
                            }
                        }
                    },
                    { field: 'BusinessUserName', title: '业务员', align: 'left', width: 100 },
                    { field: 'DeliveryUserId', visible: false },
                    { field: 'DeliveryUserName', title: '送货员', align: 'left', width: 100 },
                    { field: 'TerminalName', title: '客户', align: 'left', width: 150 },
                    //{ field: 'TerminalAddress', title: '客户地址', align: 'left', width: 200 },
                    {
                        field: 'OrderAmount',
                        title: '订单金额',
                        align: 'right',
                        width: 70
                    },
                    { field: 'OrderQuantityView', title: '商品数量', align: 'left', width: 80 },
                    { field: 'VerificationCode', title: '验证码', align: 'left', width: 70 },
                    {
                        field: 'ReversedStatus',
                        title: '单据状态',
                        align: 'center',
                        width: 70,
                        formatter: function (value, row, index) {
                            if (value) {
                                return '<span class="label label-danger">已红冲</span>';
                            } else {
                                return '<span class="label label-success">已调度</span>';
                            }
                        }
                    },
                    {
                        field: 'SignStatus',
                        title: '签收状态',
                        align: 'center',
                        width: 70,
                        //formatter: function (value, row, index) {
                        //    if (value) {
                        //        return '<span class="label label-success">已签收</span>';
                        //    } else {
                        //        return '<span class="label label-default">未签收</span>';
                        //    }
                        //}
                    },
                    {
                        field: 'SignStatus',
                        title: '数据来源',
                        align: 'center',
                        width: 70,
                        //formatter: function (value, row, index) {
                        //    if (value == 0) {
                        //        return '<span class="label label-info">线上</span>';
                        //    } else {
                        //        return '<span class="label label-info">线下</span>';
                        //    }
                        //}
                    },
                    {
                        width: 100,
                        field: 'operate',
                        title: '操作',
                        align: 'center',
                        events: operateEvents,
                        formatter: function (value, row, index) {
                            return [
                                '<button type="button" class="btn btn-sm btn-danger rowPrint">打印分拣</button>'
                            ].join('');
                        }
                    }
                ],
                onPageChange: function (number, size) {
                    m_pagerow = (number - 1) * size;
                },
                treeShowField: 'Name',
                parentIdField: 'ParentId',
                onLoadSuccess: function (data)
                {
                    $("#badge2").html($($table2).bootstrapTable('getData').length);
                    $table2.treegrid({
                        //initialState: 'collapsed',
                        treeColumn: 1,
                        expanderExpandedClass: 'glyphicon glyphicon-minus',
                        expanderCollapsedClass: 'glyphicon glyphicon-plus',
                        onChange: function () {
                            $table.bootstrapTable('resetWidth');
                        }
                    });
                },
            });

            //***
            oTableInit.InitSubTable = function (index, row, $detail) {
                //查询参数
                var dbQueryParams2 = function (params) {
                    var temp =
                    {
                        //单据号
                        billId: row.Id,
                        pageSize: params.limit,   //页面显示行数
                        pageIndex: (params.offset / params.limit)  //页码
                    };
                    return temp;
                };

                var cur_table = $detail.html('<table id="dataView" style="table-layout:fixed;"></table>').find('table');
                $(cur_table).bootstrapTable({
                    url: "/DispatchBill/AsyncDetail",
                    method: 'get',
                    //toolbar: '#toolbar',
                    striped: true,
                    cache: false,
                    pagination: true,
                    sortable: true,
                    sortOrder: "asc",
                    queryParams: dbQueryParams2,
                    sidePagination: "server",
                    idField: 'Id',
                    pageNumber: 1,
                    pageSize: 25,
                    pageList: [10, 25, 50, 100],
                    search: false,
                    //strictSearch: true,
                    //showColumns: true,
                    //showRefresh: true,
                    //minimumCountColumns: 2,
                    clickToSelect: true,
                    uniqueId: "Id",
                    //showToggle: true,
                    cardView: false,
                    detailView: false,
                    columns: [
                        //{ checkbox: true },
                        {
                            field: 'BillNumber',
                            title: '编号',
                            align: 'left',
                            width: 200,
                            formatter: function (value, row, index) {
                                if (row.BillTypeId == 11) {
                                    return [
                                        '<a  href="/SaleReservationBill/Edit/' + row.BillId + '">' + row.BillNumber + '</a>'
                                    ].join("")
                                } else if (row.BillTypeId == 10) {
                                    return [
                                        '<a  href="/ExchangeBill/Edit/' + row.BillId + '">' + row.BillNumber + '</a>'
                                    ].join("")
                                }
                                else if (row.BillTypeId == 13) {
                                    return [
                                        '<a  href="/ReturnReservationBill/Edit/' + row.BillId + '">' + row.BillNumber + '</a>'
                                    ].join("")
                                }
                            }
                        },
                        { field: 'BillTypeName', title: '单据类型', align: 'left', width: 100 },
                        {
                            field: 'TransactionDate',
                            title: '交易时间',
                            align: 'center',
                            width: 150,
                            formatter: function (value, row, index) 
                            {
								if (value!="" && value!=undefined) {
									return $(this).dateFtt('yyyy-MM-dd hh:ss:mm', new Date(value));
								} else {
									return "";
								}
                            }
                        },
                        { field: 'BusinessUserName', title: '业务员', align: 'left', width: 100 },
                        { field: 'DeliveryUserName', title: '送货员', align: 'left', width: 100 },
                        { field: 'TerminalName', title: '客户', align: 'left', width: 150 },
                        //{ field: 'TerminalAddress', title: '客户地址', align: 'left', width: 200 },
                        {
                            field: 'OrderAmount',
                            title: '订单金额',
                            align: 'right',
                            width: 70,
                            formatter: function (value, row, index) {
                                return "<span style='color:#ffd700;'>￥</span>" + parseFloat(row.OrderAmount).toFixed(2);
                            }
                        },
                        {
                            field: 'OrderQuantityView',
                            title: '商品数量',
                            align: 'left',
                            width: 80
                        },
                        { field: 'VerificationCode', title: '验证码', align: 'left', width: 70 },
                        {
                            field: 'ReversedStatus',
                            title: '单据状态',
                            align: 'left',
                            width: 70,
                            formatter: function (value, row, index) {
                                if (value) {
                                    return '<span class="label label-danger">已红冲</span>';
                                } else {
                                    return '<span class="label label-success">已调度</span>';
                                }
                            }
                        },
                        {
                            field: 'SignStatus',
                            title: '签收状态',
                            align: 'left',
                            width: 70,
                            formatter: function (value, row, index) {
                                if (value == 0) {
                                    return '<span class="label label-default">待签收</span>';
                                }
                                if (value == 1) {
                                    return '<span class="label label-success">已签收</span>';
                                }
                                if (value == 2) {
                                    return '<span class="label label-danger">拒收</span>';
                                }
                            }
                        },
                        {
                            field: 'SignStatus',
                            title: '数据来源',
                            align: 'center',
                            width: 70,
                            formatter: function (value, row, index) {
                                if (value == 0) {
                                    return '<span class="label label-info">线上</span>';
                                } else {
                                    return '<span class="label label-info">线下</span>';
                                }
                            }
                        },
                        {
                            width: 100,
                            field: 'operate',
                            title: '操作',
                            align: 'center',
                            events: operateEvents,
                            formatter: operateFormatter
                        }
                    ],
                    formatLoadingMessage: function () {
                        return "<img src='@LayoutExtensions.ResourceServerUrl("/content/images/loading.gif")'>";
                    },
                });

                $(cur_table).find('thead').css('display', 'none');

                var result = $('.detail-view');
                if (result && result.length > 0) {
                    for (var i = 0; i < result.length; i++) {
                        result[i].cells[0].style.cssText = 'padding-left:30px; padding-right:0px;';
                    }
                }
            };
            //***

            // 格式化按钮
            function operateFormatter(value, row, index) {
                return [
                    '<button type="button" class="btn btn-sm btn-info rowreset">重置</button>',
                    '<button type="button" class="btn btn-sm btn-success rowsend">发送</button>'
                ].join('');
            }


            //获取用户选择的数据
            function GetSelectData() {
                var selectDatas = [];
                var arrselections = $("#datatable1").bootstrapTable('getSelections');
                if (arrselections.length > 0)
                {
                    arrselections.forEach(function (a, b, c)
                    {
                        selectDatas.push(a);
                    });
                }
                return selectDatas;
            }

            //调度
            $("#btn_dispatchBill").click(function () {
                var selectDatas = GetSelectData();
                if (selectDatas.length == 0) {
                    $(this).showToastr('请选择有效单据！');
                    return;
                }
                var actionUrl = "/DispatchBill/Dispatch";
                var param = { datas: selectDatas };
                $(this).showModalV3("POST", $("#DispatchBillWindows"), actionUrl, param, "调度", $("#DispatchBillForm"), function () { });
            });

            //设置仓库
            $("#btn_setwarehouse", $formSection).click(function () {

                var actionUrl = "/DispatchBill/SetWareHouse";
                //这里默认设置当前经销商 所有 没有仓库 的 销售订单，退货订单
                var billtype = "";
                var ids = "";

                var param = { billtype: billtype, ids: ids, };
                $(this).showModalV2($("#SetWareHouseWindow"), actionUrl, param, "设置仓库", $("#SetWareHouseForm"), function () {
                    $('#btnSave_' + $("#SetWareHouseWindow").attr("id") + '').unbind("click").bind('click', function () {

                        //表单验证
                        jQuery.validator.addMethod("notZero", function (value, element, param) {
                            return this.optional(element) || (value != 0);
                        }, "请确保输入的值不为零");

                        var validator = $("#SetWareHouseForm").validate({
                            /* @@validation states + elements
                            ------------------------------------------- */
                            errorClass: "text-danger",
                            validClass: "text-success",
                            errorElement: "em",
                            /* @@validation rules
                            ------------------------------------------ */
                            rules: {
                                WareHouseId: {
                                    required: true
                                }
                            },
                            messages: {
                                WareHouseId: {
                                    required: '仓库不能为空'
                                }

                            },
                            /* @@validation highlighting + error placement
                            ---------------------------------------------------- */
                            highlight: function (element, errorClass, validClass) {
                                $(element).closest('.field').addClass(errorClass).removeClass(validClass);
                            },
                            unhighlight: function (element, errorClass, validClass) {
                                $(element).closest('.field').removeClass(errorClass).addClass(validClass);
                            },
                            errorPlacement: function (error, element) {
                                if (element.is(":radio") || element.is(":checkbox")) {
                                    element.closest('.option-group').after(error);
                                } else {
                                    //error.insertAfter(element.parent());
                                    element.parent().append(error);
                                }
                            },
                            submitHandler: function (form) {
                                //alert("submitted");
                                form.submit();
                            }
                        });

                        $(this).saveModalV3($("#SetWareHouseWindow"), "/DispatchBill/List", $("#SetWareHouseForm"));
                    });
                });
            });

            //查询
            $("#btn_query", $formSection).click(function () {
                m_pagerow = 0;
                $("#datatable1").bootstrapTable('refresh', { url: actionURL1 });
                $("#datatable2").bootstrapTable('refresh', { url: actionURL2 });
            });

            //调度状态改变
            $("#DispatchStatus").change(function () {
                m_pagerow = 0;
                $("#datatable1").bootstrapTable('refresh', { url: actionURL1 });
                $("#datatable2").bootstrapTable('refresh', { url: actionURL2 });
            });

            //客户搜索
            $(document).on('click', "#btn_search_customer", function () {
                var actionUrl = "/Terminal/AsyncSearchSelectPopup";
                $(this).showModalV2($("#TerminalSelectModalWindow"), actionUrl, { ids: "" }, "选择终端", $("#TerminalSelectForm"), function (rows) { });
            });

            window.operateEventsPopTerminal =
            {
                'click .rowSelect': function (e, value, row, index) {
                    try {
                        $("#TerminalId").val(row.Id);
                        $("#TerminalName").val(row.Name);
                        $('#TerminalSelectModalWindow').modal('hide');
                    }
                    catch (err) {
                        console.log(err);
                        $(this).showToastr(err);
                        return;
                    }
                }
            };
        });
         //打印前做备份,打印后会将modal dom销毁  ----只能设置全局变量，用深拷贝不行。需要深入谅解
        var printModalWindow = null;
        var printModalForm = null;
        //初始化操作按钮的方法
        window.operateEvents = {
            'click .rowreset': function (e, value, row, index) {
                WinMsg.confirm({ message: "确认要重置验证码吗？" }).on(function (e) {
                    if (!e) {
                        return;
                    }
                    var actionUrl = "/DispatchBill/Reset?id=" + row.Id;
                    window.location.href = actionUrl;
                });
            },
            'click .rowsend': function (e, value, row, index) {
                var actionUrl = "/DispatchBill/Send?id=" + row.Id;
                window.location.href = actionUrl;
            },
            'click .rowPrint': function (e, value, row, index)
            {
                var selectDatas = [];
                selectDatas.push(row);
                console.log(row);
                if (selectDatas.length==0) {
                    $(this).showToastr('请选择项目');
                    return;
                }
                var actionUrl = "/DispatchBill/Dispatch?billStatus=true&dispatchBillId=" + row.Id;
                var param = { datas: selectDatas };
                //打印前做备份,打印后会将modal dom销毁
                if (printModalWindow == null) {
                    printModalWindow = $("#DispatchBillWindows");
                }
                 //打印前做备份,打印后会将modal dom销毁
                if (printModalForm == null) {
                    printModalForm = $("#DispatchBillForm");
                }
                $(this).showModalV3("POST", printModalWindow, actionUrl, param, "调度", printModalForm, function () { });
            }
        };

        //用户修改客户名称，将客户Id置零
        $("#TerminalName").bind("change", function () {
            $("#TerminalId").val("");
        });

    </script>
}
